<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>欢迎登录</h2>
        <p>在线商城购物系统</p>
      </div>
      
      <div class="login-form">
        <el-form :model="loginForm" :rules="rules" ref="loginFormRef" size="large">
          <el-form-item prop="username">
            <el-input 
              v-model="loginForm.username" 
              placeholder="请输入用户名" 
              prefix-icon="el-icon-user"
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input 
              v-model="loginForm.password" 
              type="password" 
              placeholder="请输入密码" 
              show-password
              prefix-icon="el-icon-lock"
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <div class="remember-forgot">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <a href="javascript:;" class="forgot-link">忘记密码?</a>
          </div>
          
          <el-form-item>
            <el-button type="primary" class="login-button" @click="handleLogin(loginFormRef)">登录</el-button>
          </el-form-item>
          
          <div class="register-link">
            <span>还没有账号?</span>
            <a href="javascript:;" @click="goToRegister">立即注册</a>
          </div>
        </el-form>
      </div>
      
      <div class="login-footer">
        <p>Copyright © 2023 在线商城 All Rights Reserved.</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { User, Lock } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { inject } from 'vue';
import md5 from 'js-md5';

const router = useRouter();
const $axios = inject('$axios');
const loginFormRef = ref(null);
const rememberMe = ref(false);

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
});

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
  ]
});

// 登录处理
const handleLogin = async (formEl) => {
  if (!formEl) return;
  
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 构建登录数据
        const loginData = {
          username: loginForm.username,
          password: md5(loginForm.password)
        };
        
        // 发送登录请求
        const response = await $axios.post('/login', loginData);
        
        if (response.code === '200') {
          ElMessage.success('登录成功');
          
          // 保存用户信息到会话存储
          sessionStorage.setItem('user', JSON.stringify(response.data));
          
          // 如果选择了记住我，可以将用户名存储在本地存储中
          if (rememberMe.value) {
            localStorage.setItem('rememberedUsername', loginForm.username);
          } else {
            localStorage.removeItem('rememberedUsername');
          }
          
          // 跳转到首页
          router.push('/home/index');
        } else {
          ElMessage.error(response.message || '登录失败，请检查用户名和密码');
        }
      } catch (error) {
        console.error('登录出错:', error);
        ElMessage.error('登录失败，请稍后再试');
      }
    } else {
      ElMessage.warning('请正确填写登录信息');
    }
  });
};

// 跳转到注册页面
const goToRegister = () => {
  ElMessage.info('注册功能即将上线，敬请期待');
  // 如果有注册页面，可以跳转到注册页面
  // router.push('/register');
};

// 检查是否有记住的用户名
const checkRememberedUser = () => {
  const rememberedUsername = localStorage.getItem('rememberedUsername');
  if (rememberedUsername) {
    loginForm.username = rememberedUsername;
    rememberMe.value = true;
  }
};

// 页面加载时检查记住的用户
checkRememberedUser();
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.login-box {
  width: 400px;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.login-header {
  padding: 30px 20px;
  text-align: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.login-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.login-header p {
  margin-top: 10px;
  font-size: 14px;
  opacity: 0.8;
}

.login-form {
  padding: 30px;
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.forgot-link {
  color: #409EFF;
  text-decoration: none;
  font-size: 14px;
}

.forgot-link:hover {
  text-decoration: underline;
}

.login-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  border-radius: 4px;
  margin-top: 10px;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
}

.register-link a {
  color: #409EFF;
  text-decoration: none;
  margin-left: 5px;
}

.register-link a:hover {
  text-decoration: underline;
}

.login-footer {
  text-align: center;
  padding: 15px;
  font-size: 12px;
  color: #909399;
  border-top: 1px solid #ebeef5;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-box {
    width: 100%;
  }
}
</style>